package com.chengqj;

import com.chengqj.dao.UserDO;
import com.chengqj.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * Copyright © 2020年 com.qxkj. All rights reserved.
 *
 * @author chengqj
 * 声明式事务实现
 * version 1.0.0 (接口必须带上)
 * @date 2020/11/5 16:43
 */
@Service
public class UserServiceAnnotation {
    @Autowired
    private UserRepository userRepository;

    /**
     * 声明式事务 创建正常数据
     *
     * @param userDO
     * @return
     */
    @Transactional
    public UserDO createCommit(UserDO userDO) {
        userDO.setUsername("Annotation:" + userDO.getUsername());
        userRepository.save(userDO);
        return userDO;
    }
    /**
     * 声明式事务 异常返回
     *
     * @param userDO
     * @return
     */
    @Transactional
    public UserDO createRollback(UserDO userDO) {
        userDO.setUsername("Annotation:" + userDO.getUsername());
        userRepository.save(userDO);
        throw new RuntimeException();
    }

    /**
     * 获取用户数据
     * @param id
     * @return
     */
    public UserDO getUserById(Long id) {
        Optional<UserDO> userOptional = userRepository.findById(id);
         if (userOptional.isPresent()){
             return userOptional.get();
         }
         return null;
    }


}
